package org.jeecg.modules.clue.controller;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.date.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.query.QueryRuleEnum;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.clue.entity.ClueRecordTask;
import org.jeecg.modules.clue.entity.ClueTpCarConfig;
import org.jeecg.modules.clue.req.ClueTaskChannelInviteStatusReq;
import org.jeecg.modules.clue.service.IClueRecordTaskService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.clue.service.IClueUserTpCarRelateService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

/**
 * @Description: 线索任务
 * @Author: jeecg-boot
 * @Date: 2025-01-09
 * @Version: V1.0
 */
@Api(tags = "线索任务")
@RestController
@RequestMapping("/clue/clueRecordTask")
@Slf4j
public class ClueRecordTaskController extends JeecgController<ClueRecordTask, IClueRecordTaskService> {
    @Autowired
    private IClueRecordTaskService clueRecordTaskService;


    @Autowired
    private IClueUserTpCarRelateService clueUserTpCarRelateService;


    /**
     * 分页列表查询
     *
     * @param clueRecordTask
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "线索任务-分页列表查询")
    @ApiOperation(value = "线索任务-分页列表查询", notes = "线索任务-分页列表查询")
    @GetMapping(value = "/list")
    @PermissionData(pageComponent = "clue/recordTask/ClueRecordTaskList")
    public Result<IPage<ClueRecordTask>> queryPageList(ClueRecordTask clueRecordTask,
                                                       @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                       HttpServletRequest req) {


        // 自定义查询规则
        Map<String, QueryRuleEnum> customeRuleMap = new HashMap<>();
        // 自定义多选的查询规则为：LIKE_WITH_OR
        customeRuleMap.put("writeMode", QueryRuleEnum.LIKE_WITH_OR);
        customeRuleMap.put("tpCarConfigCode", QueryRuleEnum.LIKE_WITH_OR);
        customeRuleMap.put("pushStatus", QueryRuleEnum.LIKE_WITH_OR);
        customeRuleMap.put("qczjDistributeStatus", QueryRuleEnum.LIKE_WITH_OR);
        customeRuleMap.put("qczjAppealStatus", QueryRuleEnum.LIKE_WITH_OR);
        customeRuleMap.put("qczjFilterateStatus", QueryRuleEnum.LIKE_WITH_OR);
        customeRuleMap.put("qczjCheckStatus", QueryRuleEnum.LIKE_WITH_OR);
        customeRuleMap.put("xlbHandleStatus", QueryRuleEnum.LIKE_WITH_OR);
        customeRuleMap.put("xlbStoreStatus", QueryRuleEnum.LIKE_WITH_OR);
        customeRuleMap.put("xlbBuildStatus", QueryRuleEnum.LIKE_WITH_OR);
        QueryWrapper<ClueRecordTask> queryWrapper = QueryGenerator.initQueryWrapper(clueRecordTask, req.getParameterMap(), customeRuleMap);
        Page<ClueRecordTask> page = new Page<ClueRecordTask>(pageNo, pageSize);
        IPage<ClueRecordTask> pageList = clueRecordTaskService.page(page, queryWrapper);


        return Result.OK(pageList);
    }


    /**
     * 分页列表查询
     *
     * @param clueRecordTask
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "线索任务-分页列表查询")
    @ApiOperation(value = "线索任务-分页列表查询", notes = "线索任务-分页列表查询")
    @GetMapping(value = "/channelList")
    @PermissionData(pageComponent = "clue/recordTask/ChannelClueRecordTaskList")
    public Result<IPage<ClueRecordTask>> channelList(ClueRecordTask clueRecordTask,
                                                     @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                     @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                     HttpServletRequest req) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String roleCode = sysUser.getRoleCode();
        List<String> roleCodes = Arrays.asList(Optional.ofNullable(roleCode).orElse("").split(","));


        // 自定义查询规则
        Map<String, QueryRuleEnum> customeRuleMap = new HashMap<>();
        // 自定义多选的查询规则为：LIKE_WITH_OR
        customeRuleMap.put("writeMode", QueryRuleEnum.LIKE_WITH_OR);
        customeRuleMap.put("tpCarConfigCode", QueryRuleEnum.LIKE_WITH_OR);
        customeRuleMap.put("pushStatus", QueryRuleEnum.LIKE_WITH_OR);
        customeRuleMap.put("qczjDistributeStatus", QueryRuleEnum.LIKE_WITH_OR);
        customeRuleMap.put("qczjAppealStatus", QueryRuleEnum.LIKE_WITH_OR);
        customeRuleMap.put("qczjFilterateStatus", QueryRuleEnum.LIKE_WITH_OR);
        customeRuleMap.put("qczjCheckStatus", QueryRuleEnum.LIKE_WITH_OR);
        customeRuleMap.put("xlbHandleStatus", QueryRuleEnum.LIKE_WITH_OR);
        customeRuleMap.put("xlbStoreStatus", QueryRuleEnum.LIKE_WITH_OR);
        customeRuleMap.put("xlbBuildStatus", QueryRuleEnum.LIKE_WITH_OR);
        Page<ClueRecordTask> page = new Page<ClueRecordTask>(pageNo, pageSize);

        if (StringUtils.isBlank(clueRecordTask.getTpCarConfigCode())) {
            List<ClueTpCarConfig> clueTpCarConfigs = clueUserTpCarRelateService.userSelectPart();

            if (clueTpCarConfigs.isEmpty()) {
                return Result.OK(page);
            } else {
                String tpCarConfigCode = clueTpCarConfigs.parallelStream().map(ClueTpCarConfig::getCode).collect(Collectors.joining(","));
                clueRecordTask.setTpCarConfigCode(tpCarConfigCode);
            }
        }


        QueryWrapper<ClueRecordTask> queryWrapper = QueryGenerator.initQueryWrapper(clueRecordTask, req.getParameterMap(), customeRuleMap);


        IPage<ClueRecordTask> pageList = clueRecordTaskService.page(page, queryWrapper);
        List<ClueRecordTask> taskList = pageList.getRecords().stream().map(new Function<ClueRecordTask, ClueRecordTask>() {
            @Override
            public ClueRecordTask apply(ClueRecordTask clueRecordTask) {
                ClueRecordTask newClueRecordTask = new ClueRecordTask();
                BeanUtils.copyProperties(clueRecordTask, newClueRecordTask);

                // 当前角色不是 管理员
                if (!roleCodes.contains("plain_admin") && !roleCodes.contains("admin")) {
                    if (!"1".equals(clueRecordTask.getIzSync())) {
                        newClueRecordTask.setIzSync("");
                        newClueRecordTask.setChannelInviteStatus("");
                        newClueRecordTask.setChannelInviteTime(null);
                    }
                }
                return newClueRecordTask;
            }
        }).collect(Collectors.toList());
        pageList.setRecords(taskList);
        return Result.OK(pageList);
    }


    /**
     * 手动推送
     *
     * @param id
     * @return
     */
    @AutoLog(value = "线索任务-手动推送")
    @ApiOperation(value = "线索任务-手动推送", notes = "线索任务-手动推送")
    @RequiresPermissions("clue:clue_record_task:handlePush")
    @PostMapping(value = "/handlePush")
    public Result<String> handlePush(@RequestParam(name = "id", required = true) String id) {
        clueRecordTaskService.handlePush(id);
        return Result.OK("操作成功！");
    }


    /**
     * 渠道邀约状态修改
     *
     * @param id
     * @return
     */
    @AutoLog(value = "线索任务-渠道邀约状态修改")
    @ApiOperation(value = "线索任务-渠道邀约状态修改", notes = "线索任务-渠道邀约状态修改")
    @RequiresPermissions("clue:clue_record_task:channelInviteStatusUpdate")
    @PostMapping(value = "/channelInviteStatusUpdate")
    public Result<String> channelInviteStatusUpdate(@RequestParam(name = "id", required = true) String id, @RequestParam String channelInviteStatus) {
        clueRecordTaskService.channelInviteStatusUpdate(id, channelInviteStatus);
        return Result.OK("操作成功！");
    }


    /**
     * 渠道状态同步
     *
     * @param clueTaskChannelInviteStatusReq
     * @return
     */
    @AutoLog(value = "线索任务-渠道状态同步")
    @ApiOperation(value = "线索任务-渠道状态同步", notes = "线索任务-渠道状态同步")
    @RequiresPermissions("clue:clue_record_task:channelInviteStatusSync")
    @PostMapping(value = "/channelInviteStatusSync")
    public Result<String> channelInviteStatusSync(@RequestBody ClueTaskChannelInviteStatusReq clueTaskChannelInviteStatusReq) {
        clueRecordTaskService.channelInviteStatusSync(clueTaskChannelInviteStatusReq);
        return Result.OK("操作成功！");
    }


    /**
     * 添加
     *
     * @param clueRecordTask
     * @return
     */
    @AutoLog(value = "线索任务-添加")
    @ApiOperation(value = "线索任务-添加", notes = "线索任务-添加")
    @RequiresPermissions("clue:clue_record_task:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody ClueRecordTask clueRecordTask) {
        clueRecordTaskService.save(clueRecordTask);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param clueRecordTask
     * @return
     */
    @AutoLog(value = "线索任务-编辑")
    @ApiOperation(value = "线索任务-编辑", notes = "线索任务-编辑")
    @RequiresPermissions("clue:clue_record_task:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody ClueRecordTask clueRecordTask) {
        clueRecordTaskService.updateById(clueRecordTask);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "线索任务-通过id删除")
    @ApiOperation(value = "线索任务-通过id删除", notes = "线索任务-通过id删除")
    @RequiresPermissions("clue:clue_record_task:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        clueRecordTaskService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "线索任务-批量删除")
    @ApiOperation(value = "线索任务-批量删除", notes = "线索任务-批量删除")
    @RequiresPermissions("clue:clue_record_task:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.clueRecordTaskService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "线索任务-通过id查询")
    @ApiOperation(value = "线索任务-通过id查询", notes = "线索任务-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<ClueRecordTask> queryById(@RequestParam(name = "id", required = true) String id) {
        ClueRecordTask clueRecordTask = clueRecordTaskService.getById(id);
        if (clueRecordTask == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(clueRecordTask);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param clueRecordTask
     */
    @RequiresPermissions("clue:clue_record_task:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ClueRecordTask clueRecordTask) {
        return super.exportXls(request, clueRecordTask, ClueRecordTask.class, "线索任务");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequiresPermissions("clue:clue_record_task:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, ClueRecordTask.class);
    }

}
